﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using BusinessLayer.FindArtInfo;
using BusinessLayer.FindArtInfo.Entities;
using BusinessLayer.RegInfo;
using BusinessLayer.RegInfo.Entities;
using CommandLib;
using FindArtInfo.Common;
using FindArtInfo.Models;
using Resources;

namespace FindArtInfo.Controllers
{
    public class HomeController : MultiBase
    {
        //
        // GET: /Home/
        [RestoreModelStateFromTempData]
        public ActionResult Index()
        {
            //PageHomeModel model = new PageHomeModel();
            //model.CountArt = new CountArtBL().GetCountArt();
            //model.ArtistHome = new ArtistHomeBL().GetRandom();
            //model.Advertise = new AdvertiseBL().GetCurrent();
            string language = CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE);
            if (language != "english" && language != "french" && language != "german")
            {
                language = "english";
            }
            //return View(model);                        
            return Redirect(string.Format("~/{0}/language.html", language));
        }

        [HttpPost]        
        public ActionResult Search(PageHomeModel model)
        {
            return Redirect(string.Format("~/{0}/Artists/Result?artistName={1}", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE)), HttpUtility.UrlEncode(model.HomeArtistName)));
                //, new {artistName = model.HomeArtistName});
        }

        [RestoreModelStateFromTempData]
        public ActionResult AdvancedSearch()
        {
            PageAdvancedSearchModel model = new PageAdvancedSearchModel();
            model.ListCountry = new BusinessLayer.FindArtInfo.CountryBL().GetAll();
            return View(model);
        }

        [HttpPost]
        public ActionResult AdvancedSearch(PageAdvancedSearchModel model)
        {
            if(!string.IsNullOrEmpty(model.AdvanceSearchPriceTitle))
            {
                return Redirect(string.Format("~/{0}/Prices/Result?priceTitle={1}", Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE)), HttpUtility.UrlEncode(model.AdvanceSearchPriceTitle)));
                //return RedirectToAction("Result", "Prices", new { priceTitle = model.AdvanceSearchPriceTitle });
            }
            return
                Redirect(string.Format("~/{0}/Artists/Result?artistName={1}&born={2}&die={3}&countryId={4}",
                                       Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE)),
                                       HttpUtility.UrlEncode(model.AdvanceSearchArtistName), model.AdvanceSearchBorn, model.AdvanceSearchDie,
                                       model.AdvanceSearchCountryId));
            //return RedirectToAction("Result", "Artists", new { artistName = model.AdvanceSearchArtistName, born = model.AdvanceSearchBorn, die = model.AdvanceSearchDie, countryId = model.AdvanceSearchCountryId });
        }

        [HttpPost]
        [SetTempDataModelState]
        public ActionResult Index(PartialMenuLeftModel model)
        {            
            PageHomeModel pageHomeModel = new PageHomeModel();
            pageHomeModel.CountArt = new CountArtBL().GetCountArt();
            pageHomeModel.ArtistHome = new ArtistHomeBL().GetRandom();
            Account account = new AccountBL().GetByEmail(model.Email);
            if (account == null)
            {
                new LoginLogBL().Insert(new LoginLog
                {
                    Email = model.Email,
                    PassWord = model.PassWord,
                    Ip = Utils.GetPublicIP(),
                    Status = Constants.LoginStatus.ERROR
                });
                ModelState.AddModelError("MessageResultLogin", Multi.PageLoginHomeErrorEmail);
                return Redirect(model.ReturnUrl);
                //return View("Index", pageHomeModel);
            }
            if (!account.PassWord.Equals(model.PassWord))
            {
                new LoginLogBL().Insert(new LoginLog
                {
                    Email = model.Email,
                    PassWord = model.PassWord,
                    Ip = Utils.GetPublicIP(),
                    Status = Constants.LoginStatus.ERROR
                });
                ModelState.AddModelError("MessageResultLogin", Multi.PageLoginHomeErrorPass);
                return Redirect(model.ReturnUrl);
                //return View("Index", pageHomeModel);
            }
            if (account.Status == Constants.StatusAccount.IS_NOT_ACTIVE)
            {
                ModelState.AddModelError("MessageResultLogin", Multi.PageLoginHomeErrorActive);
                Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
                return Redirect(string.Format("~/{0}/register-again.html",
                                              Utils.GetUrlByLanguage(
                                                  CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            if (account.StartDate == null || account.EndDate == null)
            {                                    
                int result;
                new AccountBL().ActiveAccount(account.Id, out result);                
                if(result < 0)
                {
                    ModelState.AddModelError("MessageResultLogin", Multi.PageLoginHomeActiveAccountError);
                    return View("Index", pageHomeModel);
                }
                else
                {
                    //send email
                    //string subject = "Access to FindArtInfo.com";
                    //string content = string.Format("Dear {0},<p>Thank you for subscribing FindArtInfo.com</p><p>Please use the following information to login:</p><p>Username : {1}</p><p>Password : {2}</p><p>It is imperative that you maintain complete secrecy of your login and password.</p><p>We do hope you enjoy the website and that the content is both useful and enlightening</p><p>If you have any question or encounter any problem logging in, please contact a site administrator!</p><p>The FindArtInfo Team</p><hr style='color:#789FCC'/><p>This is an automatic email.</p><p>Please do not reply to this email. If you would like to contact FindArtInfo, please write to us at <br><a href='mailto:contact@findartinfo.com'>contact@findartinfo.com</a>, <a href='mailto:info@findartinfo.com'>info@findartinfo.com</a><br>", account.LastName, account.Email, account.PassWord);
                    //Utils.SendMail(Config.FromEmail, Config.DiplayFromName, Config.PassFromEmail, model.Email,
                    //                        model.Email, Config.EmailCC, subject, content, Config.Host, Convert.ToInt32(Config.Port));
                    //end
                }
            }
            account = new AccountBL().GetById(account.Id);
            DateTime dateTimeNow = new CommonBL().GetDateTimeNow();
            TimeSpan timeSpan = Convert.ToDateTime(account.EndDate) - dateTimeNow;
            if (timeSpan.Days < 0)
            {
                Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
                return Redirect(string.Format("~/{0}/renew.html",
                                              Utils.GetUrlByLanguage(
                                                  CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
            }
            Session[Constants.SessionKey.SESSION_USER_LOGIN] = account;
            Session[Constants.SessionKey.SESSION_USER_LOGIN_PAID] = account;
            new LoginLogBL().Insert(new LoginLog
                                {
                                    Email = model.Email,
                                    PassWord = model.PassWord,
                                    Ip = Utils.GetPublicIP(),
                                    Status = Constants.LoginStatus.SUCCESS
                                });
            return Redirect(model.ReturnUrl);
            //return Redirect(string.Format("~/{0}/home.html",
            //                           Utils.GetUrlByLanguage(CookiesStore.GetCookies(Constants.Cookie.COOKIE_LANGUAGE))));
                       
        }

        [RestoreModelStateFromTempData]
        public ActionResult English()
        {
            PageHomeModel model = new PageHomeModel();
            model.CountArt = new CountArtBL().GetCountArt();
            model.ArtistHome = new ArtistHomeBL().GetRandom();
            model.Advertise = new AdvertiseBL().GetCurrent();            
            return View(model);
        }

        [RestoreModelStateFromTempData]
        public ActionResult French()
        {
            PageHomeModel model = new PageHomeModel();
            model.CountArt = new CountArtBL().GetCountArt();
            model.ArtistHome = new ArtistHomeBL().GetRandom();
            model.Advertise = new AdvertiseBL().GetCurrent();                        
            return View(model);
        }

        [RestoreModelStateFromTempData]
        public ActionResult German()
        {
            PageHomeModel model = new PageHomeModel();
            model.CountArt = new CountArtBL().GetCountArt();
            model.ArtistHome = new ArtistHomeBL().GetRandom();
            model.Advertise = new AdvertiseBL().GetCurrent();                       
            return View(model);
        }

        public ActionResult Language(string l)
        {                                    
            if(l != "english" && l != "french" && l != "german")
            {
                l = "english";
            }            
            CookiesStore.SetCookies(Constants.Cookie.COOKIE_LANGUAGE, l, 365);
            return Redirect(string.Format("~/{0}.html",l));                    
        }

    }
}
